package app.server.project.core.msgdispatcher;

import app.server.project.core.tcp.model.TcpOnline;
import app.server.project.core.tcp.model.TcpReqModel;
import app.server.project.core.tcp.model.TcpRespModel;
import cn.hutool.json.JSONUtil;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Objects;

@Component
@Slf4j
public class Dispatcher {

    private final static int CLASS_POS=1;

    @Autowired
    private ApplicationContext applicationContext;
    private HashMap<Integer, FunInfo> methodHashMap=new HashMap<>();
    @PostConstruct
    public void init(){
        applicationContext.getBeansWithAnnotation(TcpController.class).forEach((k,v)->{
            for (var method:v.getClass().getDeclaredMethods()){
                var ret=method.getAnnotation(TcpReq.class);
                if (Objects.nonNull(ret)){
                    log.info("加载到tcp方法:cmd:{}",ret.cmd());
                    if (this.methodHashMap.containsKey(ret.cmd())){
                        throw new RuntimeException("出现重复方法:"+ret.cmd()+"=====methodName"+method);
                    }else {
                        //获取参数类型,方便转json
                        int num=method.getParameterCount()-1;
                        Class type=null;
                        switch (num){
                            case CLASS_POS :{
                                //第一个参数固定是id
                                type=method.getParameters()[CLASS_POS].getType();
                            }
                            break;
                        }
                        this.methodHashMap.put(ret.cmd(),FunInfo.of(type,MethodInfo.of(method,v)));
                    }
                }
            }
        });
    }

    public FunInfo getMethodByCmd(int cmd){
        var methodInfo=this.methodHashMap.get(cmd);
        return methodInfo;
    }


    public static void main(String[] ar){
        String json="{\n" +
                "    \"cmd\": 999,\n" +
                "    \"data\": {\n" +
                "\"pc\":9999\n" +
                "}\n" +
                "\n" +
                "}";

        TcpReqModel tcpReqModel=TcpReqModel.of(333, JSONUtil.toJsonStr(TcpOnline.of(222L)));

        var ss=JSONUtil.toBean(JSONUtil.toJsonStr(tcpReqModel), TcpReqModel.class);
        if (JSONUtil.isTypeJSONObject(ss.getData())){
            log.info("=========="+ss.getData());
        }
    }
}
